<template>
	<view class="_abbr">
		<view class="public">
			<view class="detail">
				<view class="main_body_view main_body_view_title">
					<u-row>
						{{dataForm.workOrderId}}
					</u-row>
				</view>
				<view class="main_body_view">
					客户：{{dataForm.customerCompanyName}}</u-col>
				</view>
				<view class="main_body_view">
					时间：{{dataForm.preArriveCustomerTime|formatDate('MM-dd HH:mm')}}
				</view>
				<view class="main_body_view">
					联系：{{dataForm.customerCompanyConnUsername}}/{{dataForm.customerCompanyConnUserTel}}
				</view>
				<view class="main_body_view">地址：{{dataForm.province}}/{{dataForm.city}}/{{dataForm.district}}</view>
				<view class="main_body_view">{{dataForm.recycleAddress||''}}</view>
				<text class="main_body_view">备注：{{dataForm.dispWorkOrderRemark||''}}</text>
			</view>
		</view>
		<view class="public">
			<view>现场要求：<text :key="item" v-for="item in dataForm.recycleLiveRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleLiveRequestOther||"无"}}</view>
			<view>现场数据：<text :key="item" v-for="item in dataForm.recycleDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleDataDestroyTypeOther||"无"}}</view>
			<view>检测要求：<text :key="item" v-for="item in dataForm.testDeviceRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDeviceRequestOther||"无"}}</view>
			<view>检测数据：<text :key="item" v-for="item in dataForm.testDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDataDestroyTypeOther||"无"}} </view>
			<view>携带设备：<text :key="item" v-for="item in dataForm.recycleTakeDevice">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleTakeDeviceOther||"无"}}</view>
		</view>
		<view class="public">
			<u-row gutter="10" justify="space-between">
				<u-col span="4" textAlign="center" align="center">设备类别</u-col>
				<u-col span="4" textAlign="center" align="center">预计数量</u-col>
				<u-col span="4" textAlign="center" align="center">预计单位</u-col>
			</u-row>
			<view v-for="(item,index) in deviceList" :key="index" style="margin: 10rpx;">
				<u-row gutter="10" justify="space-between">
					<u-col span="4" textAlign="center" align="center">{{item.deviceTypeName}}</u-col>
					<u-col span="4" textAlign="center" align="center">{{item.count}}</u-col>
					<u-col span="4" textAlign="center" align="center" style="position: relative;  left: 40rpx;">
						{{item.unit}}</u-col>
					
				</u-row>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	export default {
		name: 'main',
		onLoad(options) {
			uni.showLoading({
				title: "正在加载中"
			})
			this.getData(options.workId);
			this.BaseUrl = getApp().globalData.baseURL;
			this.getDeviceTypeList();
			this.recycleDeviceUnit();
			// 监听生成签字的图片地址
			uni.$on('q-sign', img => {
				console.log('img', img);
				//其他操作 比如上传签字图片
				uni.uploadFile({
					url: `${this.BaseUrl}system/oss/upload`, //仅为示例，非真实的接口地址
					filePath: img,
					name: 'file',
					header: {
						Authorization: uni.getStorageSync("token")
					},
					success: (oss) => {
						const data = JSON.parse(oss.data);
						if (this.writeFlag) {
							this.enginnerWriteImages.fileUrls[0] = data.data.url;
							this.enginnerWriteImagesFileUrl = data.data.url;
						} else {
							console.log('11');
							this.userWriteImages.fileUrls[0] = data.data.url;
							this.userWriteImagesFileUrl = data.data.url;
						}
						console.log(this.enginnerWriteImages.fileUrls[0]);
						console.log(this.userWriteImages.fileUrls[0]);
						this.$nextTick();
					}
				});
			})
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				show: false,
				columns: [],
				buttonDisabled: false,
				deviceList: [],
				unitShow: false,
				unitList: [],
				unitIndex: undefined,
				proud: "",
				BaseUrl: "",
				dataForm: {}, // 数据工单
				historyList: [], //过程工单
				subForm: {
					workOrderId: null,
					method: ""
				}, //提交工单
				WorkOrderMediaBo: [], //工单文件
				arriveImages: { //到场图片
					workOrderId: '',
					mediaType: "10",
					mediaName: '到场照片',
					fileUrls: []
				},
				nowImages: {
					workOrderId: '',
					mediaType: "11",
					mediaName: '回收照片',
					fileUrls: []
				},
				baleImages: {
					workOrderId: '',
					mediaType: "14",
					mediaName: '打包照片',
					fileUrls: []
				},
				entruckingImages: {
					workOrderId: '',
					mediaType: "15",
					mediaName: '装车照片',
					fileUrls: []
				},
				enginnerWriteImages: { //工程师签字
					workOrderId: '',
					mediaType: "12",
					mediaName: '工程师签字',
					fileUrls: []
				},
				enginnerWriteImagesFileUrl: '',
				userWriteImages: { //客户签字
					workOrderId: '',
					mediaType: "13",
					mediaName: '客户签字',
					fileUrls: []
				},
				userWriteImagesFileUrl: '',
				fileList1: [], //到场照片
				fileList2: [], //现场照片
				fileList3: [], //打包照片
				fileList4: [], //装车照片
				writeFlag: undefined,
			}
		},
		methods: {
			unitConfirm(event) {
				this.deviceList[this.unitIndex].trueUnit = event.value[0];
				this.unitShow = false;
				this.changeTrue(this.deviceList[this.unitIndex]);
			},
			unitFocus(item, index) {
				console.log(item);
				console.log(index);
				this.unitIndex = index;
				this.unitShow = true;
			},
			recycleDeviceUnit() {
				request({
					url: "system/dict/data/type/recycle_device_unit",
					method: 'GET'
				}).then(res => {
					const arr = [];
					for (let s of res.data) {
						arr.push(s.dictValue)
					}
					this.unitList.push(arr);
					console.log(this.unitList);
				})
			},
			async confirm(event) {
				console.log('确定:', event);
				const form = {
					count: 0,
					deviceTypeId: event.value[0],
					deviceTypeName: event.value[0],
					remark: null,
					trueCount: 0,
					trueUnit: 0,
					unit: "PCS",
					workOrderId: this.dataForm.workOrderId
				}
				// this.deviceList.push(form);

				await request({
					url: 'system/orderDeviceTypeCount',
					method: "POST",
					data: form
				}).then(res => {
					uni.showToast({
						title: '新增成功'
					})
				})
				await this.getDevice();
				this.show = false;
			},
			cancel(event) {
				console.log(event);
				this.show = false;
				this.unitShow = false;
			},
			getDeviceTypeList() {
				request({
					url: "system/dict/data/type/recycle_device_type",
					method: 'GET'
				}).then(res => {
					const arr = [];
					for (let s of res.data) {
						arr.push(s.dictValue)
					}
					this.columns.push(arr);
					console.log(this.columns);
				})
			},
			//按钮点击状态
			buttonDis() {
				this.buttonDisabled = true;
				setTimeout(() => {
					this.buttonDisabled = false;
				}, 3000)
			},
			// 添加设备
			addAdvice() {
				this.buttonDis();
				this.show = true;
			},
			// 改变设备
			changeTrue(item) {
				console.log(item);
				request({
					url: 'system/orderDeviceTypeCount',
					data: item,
					method: "PUT"
				})
			},
			goSign(num) {
				this.writeFlag = num;
				uni.navigateTo({
					url: '/uni_modules/q-sign/pages/q-sign'
				})
			},
			save() {

			},
			sub() {
				console.log("workOrderStatusId", this.dataForm.workOrderStatusId)
				switch (this.dataForm.workOrderStatusId) {
					case "14":
						this.arriveImages.workOrderId = this.dataForm.workOrderId;
						this.subForm.method = "recycle_ing";
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.arriveImages
						})
						break;
					case "15":
						this.subForm.method = "recycle_sign";
						this.enginnerWriteImages.workOrderId = this.dataForm.workOrderId;
						this.userWriteImages.workOrderId = this.dataForm.workOrderId;
						this.baleImages.workOrderId = this.dataForm.workOrderId;
						this.entruckingImages.workOrderId = this.dataForm.workOrderId
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.enginnerWriteImages
						})
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.userWriteImages
						})
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.baleImages
						})
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.entruckingImages
						})
						break;
					case "16":
						this.subForm.method = "recycle_end";
						this.nowImages.workOrderId = this.dataForm.workOrderId;
						request({
							url: 'system/orderMedia',
							method: 'POST',
							data: this.nowImages
						})
						break;
				}

				request({
					url: 'system/order',
					method: "PUT",
					data: this.subForm
				}).then(res => {
					uni.reLaunch({
						url: '/pages/view/recycle/index'
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				console.log(lists);
				console.log(this.BaseUrl);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						console.log("upload", res);
						if (name == 1) {
							this.arriveImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						} else if (name == 2) {
							this.nowImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						} else if (name == 3) {
							this.baleImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						}  else if (name == 4) {
							this.entruckingImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						} 
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			//查询所有设备回收情况
			getDevice() {
				request({
					url: "system/orderDeviceTypeCount/list",
					method: "GET",
					data: {
						workOrderId: this.dataForm.workOrderId
					}
				}).then(res => {
					console.log('结果：', res);
					this.deviceList.length = 0;
					this.deviceList = JSON.parse(JSON.stringify(res.rows));
				})
			},
			// 请求数据
			getData(workId) {
				request({
					method: "GET",
					url: `system/order/${workId}`
				}).then(res => {
					console.log('响应：', res);
					this.dataForm = res.data;
					this.subForm.workOrderId = res.data.workOrderId;
					this.proud = res.data.workOrderStatusId - 0;
					this.demark(res.data);
					this.getDevice();
				})
			},
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "10":
							this.fileList1.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						case "11":
							this.fileList2.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						case "12":
							this.enginnerWriteImages.fileUrls[0] = dataElement.fileUrl || null;
							this.enginnerWriteImagesFileUrl = dataElement.fileUrl || null;
							break;
						case "13":
							this.userWriteImages.fileUrls[0] = dataElement.fileUrl || null;
							this.userWriteImagesFileUrl = dataElement.fileUrl || null;
							break;
						case "14":
							this.fileList3.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						case "15":
							this.fileList4.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						default:
							continue;
					}
				}
			},
			// 流程
			demark(data) {
				this.historyList.push({
					id: 0,
					descTime: data.preArriveCustomerTime,
					title: '预计上门时间',
					istrue: !!data.preArriveCustomerTime && true
				}, {
					id: 1,
					descTime: data.pickOrderTime,
					title: '接单时间',
					istrue: !!data.pickOrderTime && true
				}, {
					id: 2,
					descTime: data.arriveCustomerTime,
					title: '上门时间',
					istrue: !!data.arriveCustomerTime && true
				}, {
					id: 3,
					descTime: data.startRecycleTime,
					title: '开始回收时间 ',
					istrue: !!data.startRecycleTime && true
				}, {
					id: 4,
					descTime: data.endRecycleTime,
					title: '结束回收时间',
					istrue: !!data.endRecycleTime && true
				})
			}
		},
		filters: {

			formatDate: function(value, args) {
				var dt = new Date(value);
				if (args == 'yyyy-M-d') { // yyyy-M-d
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					return `${year}-${month}-${date}`;
				} else if (args == 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					let hour = dt.getHours();
					let minute = dt.getMinutes();
					let second = dt.getSeconds();
					return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
				} else if (args == 'yyyy-MM-dd') { // yyyy-MM-dd
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${date}`;
				} else { // yyyy-MM-dd HH:mm:ss
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					let hour = dt.getHours().toString().padStart(2, '0');
					let minute = dt.getMinutes().toString().padStart(2, '0');
					let second = dt.getSeconds().toString().padStart(2, '0');
					return `${month}-${date} ${hour}:${minute}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			// box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);

			.main_body_view {
				margin: 10upx;
			}

			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}

			.user_for {
				display: flex;
			}

			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}

			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}

			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}

			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;

			}
		}

		.write {
			display: flex;
			justify-content: space-around;

			.im {
				width: 300rpx;

				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}

		// .sub {
		// 	display: flex;
		// 	justify-content: space-around;
		// 	padding: 20rpx;

		// 	.button {
		// 		width: 300rpx;
		// 	}

		// }
	}
</style>